package test.tcp.one2one;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class OneServer {
	public static void main(String args[]) {
		ServerSocket server = null;
		try {
			// 启动服务端
			server = new ServerSocket(12345);
			System.out.println("服务器启动："
					+ server.getInetAddress().getHostAddress() + ":"
					+ server.getLocalPort());

			while (true) {
				// 监听客户端
				Socket socket = server.accept();
				System.out.println("客户端连接："
						+ socket.getInetAddress().getHostAddress() + ":"
						+ socket.getPort());

				// 输入输出流
				BufferedReader sin = new BufferedReader(new InputStreamReader(
						System.in));
				BufferedReader is = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));
				PrintWriter os = new PrintWriter(socket.getOutputStream());

				// 循环处理客户端输入
				String line;
				while ((line = is.readLine()) != null) {
					System.out.println("收到：" + line);
					if (line.equals("bye")) {
						break;
					} else {
						// 读取键盘输入并回复客户端
						os.println(sin.readLine());
						os.flush();
					}
				}

				// 关闭输入输出流
				is.close();
				os.close();

				// 关闭客户端
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭服务端
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
